package ru.uskov.trainer.model.impl;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;

import ru.uskov.trainer.MainPage;
import ru.uskov.trainer.datastore.PMF;
import ru.uskov.trainer.model.IProductDescription;
import ru.uskov.trainer.model.IProductGroup;

public class ProductGroup extends ListboxItem implements IProductGroup {
  private final Map<Long, IProductDescription> items;

  public ProductGroup(String id, String value) throws IOException {
    super(id, value);
    items = new HashMap<Long, IProductDescription>();
    long start = System.currentTimeMillis();
    PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
      String query = "select from " + ProductDescription.class.getName() + " where groupId==\"" + id + "\"";
      @SuppressWarnings("unchecked")
      List<ProductDescription> result = (List<ProductDescription>) pm.newQuery(query).execute();
      for (ProductDescription product : result) {
        items.put(product.getDBKey(), product);
      }
      if (!items.isEmpty()) {
        // all right
      } else {
        long beforeReading = System.currentTimeMillis();
        readProductsFromFile(id);
        System.out.println("***Reading information from file took: " + (System.currentTimeMillis() - beforeReading));
      }
    } finally {
      pm.close();
      System.out.println("***Getting list of all products for group took: " + (System.currentTimeMillis() - start));
    }    
  }
  
  public IProductDescription getDescriptionForId(Long id) {
    return items.get(id);
  }

  private void readProductsFromFile(String id) throws IOException {
    LineNumberReader reader = new LineNumberReader(new InputStreamReader(ProductGroup.class.getResourceAsStream("/products/" + id + ".txt"), MainPage.CODEPAGE));
    try {
      int counter = 0;
      List<ProductDescription> products = new ArrayList<ProductDescription>();
      for (String line = reader.readLine(); line != null; line = reader.readLine()) {
        products.add(new ProductDescription("" + counter, line, id));
        counter++;
      }
      PersistenceManager pm = PMF.get().getPersistenceManager();
      try {
        Collection<ProductDescription> dbProducts = pm.makePersistentAll(products);
        for (ProductDescription product : dbProducts) {
          items.put(product.getDBKey(), product);
        }
      } finally {
        pm.close();
      }
    } finally {
      reader.close();
    }    
  }

  @Override
  public List<IProductDescription> getProductItems() {
    List<IProductDescription> result= new ArrayList<IProductDescription>();
    result.addAll(items.values());
    return result;
  }
}
